package com.controller.sys;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.common.DateUtils;
import com.common.PropertiesUtils;
import com.controller.task.TaskManageController;
import com.dao.sys.SysFileMapper;
import com.model.sys.SysFile;

@Controller
public class FileController {
	static final Logger logger = LoggerFactory.getLogger(FileController.class);

	@Autowired
	SysFileMapper sysFileMapper;

	/*
	 * 采用spring提供的上传文件的方法
	 */
	@RequestMapping(value = "file/springUpload", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
		String basepath = PropertiesUtils.getValue("filepath");
		String table = request.getParameter("fileTable");
		String row = request.getParameter("fileRow");
		String fileName = request.getParameter("fileName");
		long startTime = System.currentTimeMillis();
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		String year = DateUtils.getCurrentYear();
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					File dir = new File(basepath);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					String path = basepath + "/" + row + "-" + file.getOriginalFilename();
					// 上传
					file.transferTo(new File(path));
				}
			}
		}
		// 保存附件
		HashMap<String, Object> hashMapFile = new HashMap<>();
		hashMapFile.put("fileTable", table);
		hashMapFile.put("fileRow", row);
		hashMapFile.put("fileName", fileName);
		sysFileMapper.delete(hashMapFile);
//		String[] fileList = selectedFileList.split(",");
//		for (String string : fileList) {
		SysFile fileModel = new SysFile();
		fileModel.setFileId(UUID.randomUUID().toString());
		fileModel.setFileName(fileName);
		fileModel.setFileUrl(row);
		fileModel.setFileTable(table);
		fileModel.setFileRow(row);
		fileModel.setFileCreatetime(DateUtils.getCurrentTime());
		sysFileMapper.insert(fileModel);
//		}
		return "上传成功!";
	}

	@RequestMapping(value = "file/deleteFile", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String deleteFile(HttpServletRequest request) throws IllegalStateException, IOException {
		String table = request.getParameter("fileTable");
		String row = request.getParameter("fileRow");
		String fileName = request.getParameter("fileName");
		// 保存附件
		HashMap<String, Object> hashMapFile = new HashMap<>();
		hashMapFile.put("fileTable", table);
		hashMapFile.put("fileRow", row);
		hashMapFile.put("fileName", fileName);
		sysFileMapper.delete(hashMapFile);
		return "删除成功!";
	}

	@RequestMapping(value = "file/download") // 匹配的是href中的download请求
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String basePath = PropertiesUtils.getValue("filepath");
		String id = request.getParameter("id");
		SysFile model = sysFileMapper.selectByPrimaryKey(id);
		String url = model.getFileUrl();
		String name = URLEncoder.encode(model.getFileName(), "UTF-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + name);
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 获取输入流
		bis = new BufferedInputStream(new FileInputStream(basePath + "/" + url + "-" + model.getFileName()));
		// 输出流
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		// 关闭流
		bis.close();
		bos.close();
	}

	@RequestMapping(value = "file/getFileList", produces = "text/json;charset=UTF-8") // 匹配的是href中的download请求
	@ResponseBody
	public String getFileList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String table = request.getParameter("fileTable");
		String row = request.getParameter("fileRow");
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("fileTable", table);
		hashMap.put("fileRow", row);
		List<HashMap<String, Object>> list = sysFileMapper.select(hashMap);
		String jsonString = JSON.toJSONString(list);
		logger.info("selectTasks:{}", jsonString);
		return jsonString;
	}

}
